package com.assets;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.util.Log;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.assets.databinding.ActivityShowBitmapBinding;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Allot;
import com.assets.room.entity.Allotdetail;
import com.assets.room.entity.Asset;
import com.assets.room.entity.Dept;
import com.assets.room.entity.Place;
import com.assets.room.entity.User;
import com.assets.room.entity.Worker;
import com.assets.util.IdWorkerUtil;
import com.assets.util.MyOkHttp;
import com.assets.util.RequestResult;
import com.assets.util.RequestSuccess;
import com.assets.util.Since_case;
import com.bigkoo.alertview.AlertView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;

public abstract class BaseActivity extends AppCompatActivity {
    /***是否显示标题栏*/
    private boolean isshowtitle = true;
    /***是否显示标题栏*/
    private boolean isshowstate = true;
    /***封装toast对象**/
    private static Toast toast;
    /***获取TAG的activity名称**/
    protected final String TAG = this.getClass().getSimpleName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    /*    if(!isshowtitle){
            requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        if(isshowstate){
            getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,
                    WindowManager.LayoutParams. FLAG_FULLSCREEN);
        }*/
        //设置布局
        if (intiLayout() != -1) {
            setContentView(intiLayout());
        }
        //初始化控件
        initView();
        //设置数据
        initData();
    }

    /**
     * 设置布局
     *
     * @return
     */
    public abstract int intiLayout();

    /**
     * 初始化布局
     */
    public abstract void initView();

    /**
     * 设置数据
     */
    public abstract void initData();

    /**
     * 显示短toast
     *
     * @param msg
     */
    public void showToast(final String msg) {
        runOnUiThread(() -> {
            if (toast != null) {
                toast.cancel();
            }
            toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
            toast.show();
        });
    }

    private AlertView alertView;

    public void showTipDialog(RequestResult<Boolean> result, String msg) {
        this.runOnUiThread(() -> {
            if (this.alertView == null || !this.alertView.isShowing()) {
                this.alertView = new AlertView("提示", msg, "取消", new String[]{"确认"}, (String[]) null, this, AlertView.Style.Alert, (o, position) -> {
                    this.alertView.dismissImmediately();
                    if (position == -1) {
                        result.result(false);
                    }
                    if (position == 0) {
                        result.result(true);
                    }
                });
                this.alertView.setCancelable(false);
                this.alertView.show();
            }
        });
    }


    public void showBitmap(Object o) {
        runOnUiThread(() -> {
            Dialog dialog = new Dialog(this, R.style.FullActivity);
            WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
            attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
            attributes.height = WindowManager.LayoutParams.MATCH_PARENT;
            dialog.getWindow().setAttributes(attributes);
            ActivityShowBitmapBinding binding = ActivityShowBitmapBinding.inflate(getLayoutInflater());
            binding.tvTitle.fh.setOnClickListener(v -> finish());
            binding.tvTitle.titleText.setText("图片展示");
            //binding.photoView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            Glide.with(this).load(o).into(binding.photoView);
            dialog.setContentView(binding.getRoot());
            //大图的点击事件（点击让他消失）
            dialog.show();
        });
    }

    /**
     * 打开系统相册
     */
    protected void openAlbum() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
        photoPickerIntent.addCategory(Intent.CATEGORY_OPENABLE);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, 55);
    }

    //加载进度弹窗
    private volatile ProgressDialog progressDialog;

    public void showDialog(String title) {
        runOnUiThread(() -> {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(this);
            }
            progressDialog.setTitle(title);
            progressDialog.setMessage("Loading...");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setCancelable(true);
            progressDialog.show();
        });
    }

    public void canDialog() {
        runOnUiThread(() -> {
            if (progressDialog != null) {
                if (progressDialog.isShowing()) {
                    progressDialog.cancel();
                }
            }
        });
    }

    public void post(String url, Map<String, String> map, RequestResult<String> result) {
        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("连接服务器失败");
            }

            @Override
            public void requestComplete() {
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                result.result(responseData);
                //setData(queryData);
            }
        });
    }

    public void postBitmap(String uploadAsset, File file, String assetNumber, RequestResult<String> result) {
        MyOkHttp.getInstance().postBitMap(uploadAsset, file, assetNumber, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("连接服务器失败");
            }

            @Override
            public void requestComplete() {
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                result.result(responseData);
            }
        });
    }

    protected interface result {
        void error();
    }

    public void submitPost(String url, Map<String, String> prama, RequestResult<String> result) {

        String assetNumbers = prama.get("assetNumbers");
        String division = prama.get("division");
        String inunit = prama.get("inunit");
        String remark = prama.get("remark");
        String userId = prama.get("userId");
        String place = prama.get("place");
        String admin = prama.get("admin");
        String outPlace = prama.get("outPlace");
        String jifang = prama.get("jifang");
        String jigui = prama.get("jigui");
        String newOutPlace = prama.get("newOutPlace");


        if (place.isEmpty()) {
            showToast("请选择所属地点");
            return;
        }

        Place deptById1 = MyDataBase.init(BaseActivity.this).placeDao().getAllById(place);

        if (!jigui.isEmpty() && jifang.isEmpty()) {

            showToast("请填写机房");

            return;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("state", "0");

        Allot allot = new Allot();
        SimpleDateFormat ymd = new SimpleDateFormat("yyyyMMdd");


        allot.setAllotId(Long.valueOf(IdWorkerUtil.getInstance(1L).generateUniqueId(12)));
        allot.setInunit(inunit);
        allot.setDivision(division);
        allot.setRemark(remark);
        allot.setUserId(userId);
        allot.setAdmin(admin);
        allot.setInPlace(/*place*/newOutPlace);
        allot.setOutPlace(outPlace);
        Worker worker = MyDataBase.init(BaseActivity.this).workerService().getWorkerById(admin)/*workerService.getById(admin)*/;
        if(worker != null) {
            allot.setIndept(worker.getDept());
        }
        allot.setIsfinish(place);
        allot.setStatus("2");
        allot.setIndate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        allot.setRedate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        allot.setIsFlag("1");

        MyDataBase.init(BaseActivity.this).allotService().insert(allot);

        assetNumbers = assetNumbers.substring(1, assetNumbers.length()-1);
        assetNumbers = assetNumbers.replace(" ", "");
        String[] numbers = assetNumbers.split(",");
        for(int i=0; i<numbers.length; i++){
            Allotdetail allotdetail = new Allotdetail();
            allotdetail.setAllotId(String.valueOf(allot.getAllotId()));
            allotdetail.setAssetId(numbers[i]);
            Asset asset = MyDataBase.init(BaseActivity.this).assetDao().queryAllByNumber(numbers[i]);
            if(asset!=null) {

//                if (i < 1) {
                    if (jifang.isEmpty() && jigui.isEmpty()) {
                        asset.setPlace(place);
                        asset.setTeam(MyDataBase.init(BaseActivity.this).placeDao().getNameById(place) ==null ? "/":MyDataBase.init(BaseActivity.this).placeDao().getNameById(place));
                        asset.setCompany(deptById1.getName());
                        allot.setInPlace(/*place*//*newOutPlace*/place + "");
                    }else {
                        if (!jigui.isEmpty() && jifang.isEmpty()) {
                            Place place1 = MyDataBase.init(BaseActivity.this).placeDao().getAllByName(jigui);
                            if (place1 != null) {
                                asset.setPlace(place1.getId() + "");
                                asset.setTeam(place1.getName());
                                asset.setCompany(deptById1.getName());
                                allot.setInPlace(/*place*//*newOutPlace*/place1.getId() + "");
                            }else {
                                Place placeNew = MyDataBase.init(BaseActivity.this).placeDao().getAllByName(place);
                                String pMax = MyDataBase.init(BaseActivity.this).placeDao().getMaxId();
                                Place place2 = new Place();
                                place2.setId(Integer.valueOf(pMax) + 1);
                                place2.setName(jigui);
                                place2.setBig("");
                                place2.setPid(placeNew.getId() + "");
                                place2.setFlag("1");
                                place2.setRemark(placeNew.getRemark());
                                allot.setInPlace(/*place*//*newOutPlace*/place2.getId() + "");
                                asset.setPlace(place2.getId() + "");
                                asset.setTeam(place2.getName());
                                asset.setCompany(deptById1.getName());
                                MyDataBase.init(BaseActivity.this).placeDao().insertPlace(place2);
                            }
                        }else if (jigui.isEmpty() && !jifang.isEmpty()){

                            Place place1 = MyDataBase.init(BaseActivity.this).placeDao().getAllByName(jifang);
                            if (place1 != null) {
                                asset.setPlace(place1.getId() + "");
                                asset.setTeam(place1.getName());
                                asset.setCompany(deptById1.getName());
                                allot.setInPlace(/*place*//*newOutPlace*/place1.getId() + "");
                            }else {
                                Place placeNew = MyDataBase.init(BaseActivity.this).placeDao().getAllById(place);
                                Place place2 = new Place();
                                String pMax = MyDataBase.init(BaseActivity.this).placeDao().getMaxId();
                                place2.setId(Integer.valueOf(pMax) + 1);
                                place2.setName(jifang);
                                place2.setBig("");
                                place2.setPid(placeNew.getId() + "");
                                place2.setFlag("1");
                                place2.setRemark(placeNew.getRemark());
                                allot.setInPlace(/*place*//*newOutPlace*/place2.getId() + "");
                                MyDataBase.init(BaseActivity.this).placeDao().insertPlace(place2);
                                asset.setPlace(place2.getId() + "");
                                asset.setTeam(place2.getName());
                                asset.setCompany(deptById1.getName());
                            }


                        }else if (!jigui.isEmpty() && !jifang.isEmpty()) {
                            Place placePo = new Place();
//
                            Place place1 = MyDataBase.init(BaseActivity.this).placeDao().getAllByName(jifang);
                            if (place1 == null) {
                                Place placeNew = MyDataBase.init(BaseActivity.this).placeDao().getAllById(place);
                                String pMax = MyDataBase.init(BaseActivity.this).placeDao().getMaxId();
                                placePo.setId(Integer.valueOf(/*IdWorkerUtil.getInstance(1L).generateUniqueId(6)*/pMax) + 1);
                                placePo.setName(jifang);
                                placePo.setBig("");
                                placePo.setPid(placeNew.getId() + "");
                                placePo.setFlag("1");
                                placePo.setRemark(placeNew.getRemark());
                                MyDataBase.init(BaseActivity.this).placeDao().insertPlace(placePo);
                            }

                            Place place2 = MyDataBase.init(BaseActivity.this).placeDao().getAllByName(jigui);
                            if (place2 == null) {
                                Place placeNew = MyDataBase.init(BaseActivity.this).placeDao().getAllById(placePo.getId() + "");
                                Place placex = new Place();
                                String pMax = MyDataBase.init(BaseActivity.this).placeDao().getMaxId();
                                placex.setId(Integer.valueOf(pMax) + 1);
                                placex.setName(jigui);
                                placex.setBig("");
                                placex.setPid(placeNew.getId() + "");
                                placex.setFlag("1");
                                placex.setRemark(placeNew.getRemark());
                                allot.setInPlace(/*place*//*newOutPlace*/String.valueOf(placex.getId()));
                                asset.setPlace(String.valueOf(placex.getId()));
                                asset.setTeam(placex.getName());
                                asset.setCompany(deptById1.getName());
                                MyDataBase.init(BaseActivity.this).placeDao().insertPlace(placex);
                            }else {
                                allot.setInPlace(/*place*//*newOutPlace*/String.valueOf(place2.getId()));
                                asset.setPlace(place2.getId() + "");
                                asset.setTeam(place2.getName());
                                asset.setCompany(deptById1.getName());
                            }

                        }

                    }

//                }


//                asset.setPlace(place);

                asset.setIsFlag("1");
                asset.setFinancialCode(jifang);
                asset.setAccountant(jigui == null || jigui.isEmpty() ? "/":jigui);
                allotdetail.setAllotDetailId(Long.valueOf(IdWorkerUtil.getInstance(1L).generateUniqueId(19)));
                allotdetail.setCompany(asset.getCompany());
                allotdetail.setDivision(asset.getDivision());
                allotdetail.setDept(asset.getDeptId());
                allotdetail.setIsaudit("1");
                allotdetail.setUser(Since_case.getInstance().getUserId());
                allotdetail.setIsFlag("1");
                allotdetail.setText(remark);

            }
            MyDataBase.init(BaseActivity.this).allotService().update(allot);
            MyDataBase.init(BaseActivity.this).allotdetailService().insert(allotdetail);
            MyDataBase.init(BaseActivity.this).assetDao().updateAsset(asset);
        }


        map.put("state", "1");

        result.result(new Gson().toJson(map));
    }

    public void rfidPost(String url, Map<String, String> prama, RequestResult<String> result, result error) {
//        map.put("rfid", epc);
//        map.put("userId", Since_case.getInstance().getUserId());
        String rfid_new = prama.get("rfid");
        String userId = prama.get("userId");
        if(prama.get("rfid") !=null&& prama.get("rfid").toString().length()>16) {
            rfid_new = prama.get("rfid").toString().substring(0, 16);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("state", "0");

        Asset asset = new Asset();
        asset = MyDataBase.init(BaseActivity.this).assetDao().queryAllById(rfid_new);
        if (asset == null) {
            map.put("state", "2");
        }else if (asset.getStatus().equals("2")) {
            // 资产当前状态不可调拨
            map.put("state", "3");
        }else {
            User user = MyDataBase.init(BaseActivity.this).userDao().getUserById(userId);

            Asset assetNew = MyDataBase.init(BaseActivity.this).assetDao().queryAllById(rfid_new);

            Dept dept = MyDataBase.init(BaseActivity.this).deptDao().getDeptById(assetNew.getDeptId());
            assetNew.setDeptId(dept == null ? "暂无使用部门" : dept.getSimpleName());

            assetNew.setAaa(assetNew.getPlace());

            Place place = MyDataBase.init(BaseActivity.this).placeDao().getAllById(assetNew.getPlace());
            assetNew.setPlace(place == null ? "暂无存放位置" : place.getName());


            map.put("state", "1");
            map.put("asset", assetNew);
        }

        Log.d("无敌最俊朗", "rfidPost: " + new Gson().toJson(map));
        result.result(new Gson().toJson(map));
    }

    public void rfidPostSao(String url, Map<String, String> prama, RequestResult<String> result, result error) {
//        map.put("rfid", epc);
//        map.put("userId", Since_case.getInstance().getUserId());
        String rfid_new = prama.get("rfid");
        String userId = prama.get("userId");
//        if(prama.get("rfid") !=null&& prama.get("rfid").toString().length()>16) {
//            rfid_new = prama.get("rfid").toString().substring(0, 16);
//        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("state", "0");

        Asset asset = new Asset();
        asset = MyDataBase.init(BaseActivity.this).assetDao().queryAllByIdSao(rfid_new);
        if (asset == null) {
            map.put("state", "2");
        }else if (asset.getStatus().equals("2")) {
            // 资产当前状态不可调拨
            map.put("state", "3");
        }else {
            User user = MyDataBase.init(BaseActivity.this).userDao().getUserById(userId);

            Asset assetNew = MyDataBase.init(BaseActivity.this).assetDao().queryAllByIdSao(rfid_new);

            Dept dept = MyDataBase.init(BaseActivity.this).deptDao().getDeptById(assetNew.getDeptId());
            assetNew.setDeptId(dept == null ? "暂无使用部门" : dept.getSimpleName());

            assetNew.setAaa(assetNew.getPlace() == null ? "" : assetNew.getPlace());

            Place place = MyDataBase.init(BaseActivity.this).placeDao().getAllById(assetNew.getPlace());
            assetNew.setPlace(place == null ? "暂无存放位置" : place.getName());


            map.put("state", "1");
            map.put("asset", assetNew);
        }

        Log.d("无敌最俊朗", "rfidPost: " + new Gson().toJson(map));
        result.result(new Gson().toJson(map));
    }

    public void post(String url, Map<String, String> map, RequestResult<String> result, result error) {
        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("连接服务器失败");
                error.error();
            }

            @Override
            public void requestComplete() {
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                result.result(responseData);
                //setData(queryData);
            }
        });
    }

}
